#include "stdafx.h"
#include "wtl_avatar_control.h"
#include <io.h>

namespace cm {
namespace Windows {


CAvatarCtrl::CAvatarCtrl() : m_Init(false)
{
}

LRESULT CAvatarCtrl::OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	if (m_Init == false)
	{
		GetClientRect(m_InitialRect);
		m_Init = true;
	}

	if (m_Image.IsNull())
		return DefWindowProc(uMsg, wParam, lParam);

	PAINTSTRUCT ps;
	HDC hDC = BeginPaint(&ps);

	CRect rc;
	GetClientRect(rc);

	::SetStretchBltMode(hDC,HALFTONE);

	m_Image.StretchBlt(hDC,rc);

	EndPaint(&ps);
	return 0;
};

bool CAvatarCtrl::LoadAvatarPicture(LPCTSTR szPath)
{
	m_Image.Destroy();

	HRESULT hr = m_Image.Load(szPath);

	Invalidate();
	UpdateWindow();

	return (hr == S_OK);
};

LRESULT CAvatarCtrl::OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	TRACKMOUSEEVENT t_MouseEvent;

	t_MouseEvent.cbSize      = sizeof(TRACKMOUSEEVENT);
	t_MouseEvent.dwFlags     = TME_LEAVE | TME_HOVER;
	t_MouseEvent.hwndTrack   = m_hWnd;
	t_MouseEvent.dwHoverTime = 1;

	// We Tell Windows we want to receive WM_MOUSEHOVER and WM_MOUSELEAVE
	::_TrackMouseEvent(&t_MouseEvent);

	return 0;
}

LRESULT CAvatarCtrl::OnMouseHover(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	SetTimer(1, 1, NULL);
	KillTimer(2);
	return 0;
}

LRESULT CAvatarCtrl::OnMouseLeave(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	SetTimer(2, 1, NULL);
	KillTimer(1);
	return 0;
}

LRESULT CAvatarCtrl::OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	CRect rc;
	GetWindowRect(rc);
	GetParent().ScreenToClient(rc);
	if (wParam == 1)
	{
		if (rc.Width() < m_InitialRect.Width() * 2)
		{
			rc.right  += 5;
			rc.bottom += 5;
			MoveWindow(rc);
			return 0;
		}
		KillTimer(1);
		return 0;
	}
	if (wParam == 2)
	{
		if (rc.Width() > m_InitialRect.Width())
		{
			rc.right  -= 5;
			rc.bottom -= 5;
			MoveWindow(rc);
			return 0;
		}
		KillTimer(2);
		return 0;
	}
	return 0;
}

}}
